﻿using HandyControl.Controls;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace 紧缩场反射面装调测试系统.Controll
{
    public class CheckComboBoxHelper
    {
        public static IList GetSelectedItems(DependencyObject obj)
        {
            return (IList)obj.GetValue(SelectedItemsProperty);
        }
        public static void SetSelectedItems(DependencyObject obj, int value)
        {
            obj.SetValue(SelectedItemsProperty, value);
        }
        public static readonly DependencyProperty SelectedItemsProperty =
            DependencyProperty.RegisterAttached("SelectedItems", typeof(IEnumerable), typeof(CheckComboBoxHelper), new PropertyMetadata(null, OnSelectedItemsChanged));

        private static void OnSelectedItemsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is CheckComboBox cbox)
            {
                if (e.OldValue != null)
                {

                    cbox.SelectionChanged -= OnSelectionChanged;
                }
                if (e.NewValue is IList list)
                {
                    cbox.SelectedItems.Clear();
                    if (list != null)
                    {
                        foreach (var item in list)
                        {
                            cbox.SelectedItems.Add(item);
                        }
                        cbox.OnApplyTemplate();
                        cbox.SelectionChanged += OnSelectionChanged;
                    }
                }
            }
        }

        private static void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var dp = sender as DependencyObject;
            if (dp == null) return;
            var dataSource = GetSelectedItems(dp);

            // 添加用户选中的项
            foreach (var item in e.AddedItems)
            {
                //防止重复添加
                bool add = true;
                foreach (var temp in dataSource)
                {
                    if ((string)temp == (string)item)
                    {
                        add = false;
                    }
                }
                if (add)
                {
                    dataSource.Add(item);
                }
            }
            // 删除用户取消选中的项
            foreach (var item in e.RemovedItems)
            {
                dataSource.Remove(item);
            }
        }
    }
}
